<template>
  <div class="main">
    <div class="topTitle">{{ props.title }}</div>
    <div class="form_content">
      <NScrollbar>
        <NSpin :show="spinShow">
          <div class="content">
            <div class="top-select">
              <div class="select-item" v-for="(item, index) in supplementaryTypeList" :key="index"
                @click="getTopTic(index, item.dicCode)" :class="selectedIndex == index ? 'active' : ''">
                <NImage :src="handleSrc(index, item.dicCode)" style="width: 20rem; height: 20rem" preview-disabled>
                </NImage>
                <div style="margin-left: 10rem">{{ item.dicName }}</div>
              </div>
            </div>

            <div class="progressHint" v-if="hint">
              <NIcon size="20" class="iconStyle">
                <ErrorRound />
              </NIcon>
              <div style="white-space: pre-wrap" v-html="hint"></div>
            </div>
            <div class="progress">
              <div style="display:flex; margin-right: 10rem;">
                <NIcon :size="20" class="iconStyle">
                  <ApprovalFilled />
                </NIcon>
                <span>审批流程</span>
              </div>
              <span style="font-size: 18rem;flex: 1;" :style="{ color: !workFlowList ? 'red' : '#79bb92' }">
                {{ workFlowList ? workFlowList : '暂无配置流程，请联系管理员进行配置' }}
              </span>
            </div>

            <div class="content_cen">
              <NForm ref="formRef" require-mark-placement="left" label-placement="left" :rules="rules" :label-width="110"
                label-align="right" :model="formValue" style="width: 350rem">

                <NFormItem label="目的地:" path="destination" v-if="formValue.leaveType == 'A2605'">
                  <NSelect :options="[
                    { label: '杭州市内', value: '杭州市内' },
                    { label: '省外', value: '省外' },
                    { label: '省内杭州市外', value: '省内杭州市外' }
                  ]" class="commonWidth" clearable v-model:value="formValue.destination"
                    @update-value="handleUpdateValue" />
                </NFormItem>

                <NFormItem label="几孩:" path="childCon" v-if="formValue.leaveType == 'A2606'">
                  <NSelect :options="[
                    { label: '一孩', value: '一孩' },
                    { label: '二孩/三孩', value: '二孩/三孩' }
                  ]" class="commonWidth" clearable v-model:value="formValue.childCon"
                    @update-value="handleUpdateValue" />
                </NFormItem>

                <NFormItem label="开始时间:" path="startDate">
                  <NDatePicker input-readonly placeholder="开始时间" clearable class="commonWidth" type="date"
                    v-model:formatted-value="formValue.startDate" :on-update:formatted-value="handleStartDate"
                    :disabled="formValue.leaveType == 'A2605' && !formValue.destination"
                    :is-date-disabled="handleDateDisableStart" :on-clear="clearStartDate" />
                  <NSelect :options="[
                    { label: '上午', value: '上午' },
                    { label: '下午', value: '下午' }
                  ]" style="margin-left: 20rem; width: 130rem" v-model:value="formValue.startSessional" v-if="['A2601', 'A2602', 'A2603', 'A2608', 'A2609', 'A2610'].includes(
  formValue.leaveType
)
  " />
                </NFormItem>

                <NFormItem label="结束时间:" path="endDate">
                  <NDatePicker input-readonly placeholder="结束时间" clearable class="commonWidth" type="date"
                    v-model:formatted-value="formValue.endDate" :is-date-disabled="handleDateDisable"
                    :disabled="disableArr.includes(formValue.leaveType)" @update-formatted-value="handleEndTime" />
                  <NSelect :options="[
                    { label: '上午', value: '上午' },
                    { label: '下午', value: '下午' }
                  ]" style="margin-left: 20rem; width: 130rem" v-model:value="formValue.endSessional" v-if="['A2601', 'A2602', 'A2603', 'A2608', 'A2609', 'A2610'].includes(
  formValue.leaveType
)
  " />
                </NFormItem>

                <NFormItem label="可用调休假:" style="margin-bottom: 10rem" :show-feedback="false"
                  v-if="formValue.leaveType == 'A2601'">
                  <span>{{ userLeaveList.txj }}天</span>
                </NFormItem>

                <NFormItem label="产假天数:" style="margin-bottom: 10rem" :show-feedback="false"
                  v-if="formValue.leaveType == 'A2606'">
                  <span>{{ formValue.childCon != '一孩' ? '188天' : '158天' }}</span>
                </NFormItem>

                <NFormItem label="陪产假天数:" style="margin-bottom: 10rem" :show-feedback="false"
                  v-if="formValue.leaveType == 'A2607'">
                  <span>15天</span>
                </NFormItem>

                <NFormItem label="剩余年休假:" style="margin-bottom: 10rem" :show-feedback="false"
                  v-if="['A2602', 'A2603'].includes(formValue.leaveType)">
                  <span>{{ userLeaveList.nxj }}天</span>
                </NFormItem>

                <NFormItem label="剩余陪护假:" style="margin-bottom: 10rem" :show-feedback="false"
                  v-if="formValue.leaveType == 'A2609'">
                  <span>{{ userLeaveList.phj }}天</span>
                </NFormItem>

                <NFormItem label="剩余育儿假:" style="margin-bottom: 10rem" :show-feedback="false"
                  v-if="formValue.leaveType == 'A2608'">
                  <span>{{ userLeaveList.yej }}天</span>
                </NFormItem>

                <NFormItem label="请假天数:" :show-feedback="false" style="margin-bottom: 10rem" v-if="['A2601', 'A2602', 'A2603', 'A2604', 'A2605', 'A2608', 'A2609', 'A2610'].includes(
                  formValue.leaveType
                )
                  ">
                  <span>{{ formValue.leaveDay }}天</span>
                </NFormItem>

                <NFormItem label="请假原因:" path="leaveReason">
                  <NInput placeholder="请输入请假原因" style="width: 360rem; min-height: 100rem" type="textarea"
                    v-model:value="formValue.leaveReason" clearable :allow-input="noSideSpace" />
                </NFormItem>

                <NFormItem label="附件:" path="fileIds">
                  <VUpload :file-list="fileList" @getList="handleUploadList" />
                </NFormItem>
              </NForm>
            </div>
          </div>
        </NSpin>
      </NScrollbar>
    </div>
  </div>
  <FixedAction>
    <div style="display: flex">
      <NSpace justify="start" style="flex: 0 0 42%">
        <NButton style="width: 78px; color: #5fb17f" ghost @click="goBack">
          <template #icon>
            <img :src="VBackImg" style="width: 25rem; height: 25rem" />
          </template>
          返回
        </NButton>
      </NSpace>

      <NSpace justify="center">
        <NButton type="primary" style="background-color: #5faab1;" @click="confirm(true)" :loading="loading"
          v-if="formValue.entityId">
          保存草稿
        </NButton>
        <NButton type="primary" @click="confirm(false)" :loading="loading" v-if="formValue.entityId">
          提交申请
        </NButton>
      </NSpace>
    </div>
  </FixedAction>

  <NModal :auto-focus="false" v-model:show="contentVisible" @close="contentVisible = false">
    <VDialogContent @close="contentVisible = false" @submit="contentVisible = false" title="保存提示">
      <div style="width: 300rem; height: 100rem; text-align: center;display: flex;align-items: center">
        {{ contentContent }}
      </div>
      <div style="text-align: center;" v-if="repeatFormUrl.path !== ''">
        <NButton type="primary" text style="font-size: 14px;" @click="openRepeatUrl()">
          点此
        </NButton>查看重复工单
      </div>
    </VDialogContent>
  </NModal>
</template>

<script setup lang="ts">
import { ref, reactive, watch, onMounted } from 'vue'
import {
  NSpace, NForm, NInput, NFormItem, NSelect, NButton, NScrollbar,
  NModal, useMessage, NDatePicker, NSpin, NIcon, NImage
} from 'naive-ui'
import type { FormInst } from 'naive-ui'
import router from '@/router'
import { useTagStore } from '@/stores/layout'
import FixedAction from '@/components/FixedAction.vue'
import VUpload from '@/views/OA/Common/Upload.vue'
import { sendRequest } from '@/utils/api'
import type { HttpResponse } from '@/utils/http'
import type { LeaveModel } from '@/api/leave'
import { useRoute } from 'vue-router'
import VDialogContent from '@/views/OA/Common/DialogContent.vue'
import { ApprovalFilled, ErrorRound } from '@vicons/material'
import { format, subDays, addDays, differenceInDays } from 'date-fns'
import VBackImg from '@/assets/images/back.png'
import A2601 from '@/assets/images/调休@2x.png'
import A2601F from '@/assets/images/调休1@2x.png'
import A2602 from '@/assets/images/年休假@2x.png'
import A2602F from '@/assets/images/年休假1@2x.png'
import A2603 from '@/assets/images/事假 @2x.png'
import A2603F from '@/assets/images/事假1@2x.png'
import A2604 from '@/assets/images/婚假@2x.png'
import A2604F from '@/assets/images/婚假1@2x.png'
import A2605 from '@/assets/images/丧假 @2x.png'
import A2605F from '@/assets/images/丧假1@2x.png'
import A2606 from '@/assets/images/产假@2x.png'
import A2606F from '@/assets/images/产假1@2x.png'
import A2607 from '@/assets/images/陪产假@2x.png'
import A2607F from '@/assets/images/陪产假1@2x.png'
import A2608 from '@/assets/images/育儿假@2x.png'
import A2608F from '@/assets/images/育儿假1@2x.png'
import A2609 from '@/assets/images/陪护假@2x.png'
import A2609F from '@/assets/images/陪护假1@2x.png'
import A2610 from '@/assets/images/病假@2x.png'
import A2610F from '@/assets/images/病假1@2x.png'
const disableArr = ref(['A2604', 'A2606', 'A2607'])

const tags = useTagStore().tags
const route = useRoute()
const props = defineProps({
  title: { type: String, default: () => '请假申请' },
  id: { type: [Number, String], default: () => null },
  flat: { default: () => false },
  type: { type: String }
})
const message = useMessage()

const formValue = reactive<Record<string, any>>({
  startDate: null, //开始日期
  startSessional: '上午', //开始上下午
  endDate: null, //结束日期
  endSessional: '下午', //结束上下午
  destination: null, //目的地
  childCon: null, //几孩
  fileIds: null, //附件
  draftFlag: null, //草稿状态
  entityId: null, //流程实体id
  leaveDay: 0, //请假天数
  leaveReason: null, //请假原因
  leaveType: 'A2601' //请假类型
})
const rules: any = ref({
  startDate: {
    required: true,
    message: '请选择开始日期',
    trigger: ['select', 'change']
  },
  endDate: {
    required: true,
    message: '请选择结束日期',
    trigger: ['select', 'change']
  },
  destination: {
    required: true,
    message: '请选择目的地',
    trigger: ['select', 'change']
  },
  childCon: {
    required: true,
    message: '请选择几孩',
    trigger: ['select', 'change']
  },
  leaveReason: {
    required: true,
    trigger: ['input', 'blur'],
    validator: (_: any, value: any) => {
      if (!value) return new Error('请输入请假原因')
      if (value?.length > 100) return new Error('请假原因字数不得超过100')
      return true
    }
  },
  fileIds: {
    required: false,
    message: '请选择附件',
    trigger: ['change']
  }
})
// 限制前后空格
const noSideSpace = (value: string) => !value.startsWith(' ') && !value.endsWith(' ')
// 丧假产假选择重置时间
const handleUpdateValue = () => {
  formValue.startDate = null
  formValue.endDate = null
}
// 开始时间选择
const handleStartDate = async (val: any) => {
  formValue.startDate = val
  if (!val) return
  if (formValue.leaveType == 'A2604')
    formValue.endDate = format(new Date(addDays(new Date(formValue.startDate), 2)), 'yyyy-MM-dd')//3
  if (formValue.leaveType == 'A2604')
    formValue.endDate = format(new Date(addDays(new Date(formValue.startDate), 2)), 'yyyy-MM-dd')//3
  if (formValue.leaveType == 'A2607')
    formValue.endDate = format(new Date(addDays(new Date(formValue.startDate), 14)), 'yyyy-MM-dd')//15
  else if (formValue.leaveType == 'A2606') {
    if (formValue.childCon == '一孩')
      formValue.endDate = format(
        new Date(addDays(new Date(formValue.startDate), 157)),//158
        'yyyy-MM-dd'
      )
    else
      formValue.endDate = format(
        new Date(addDays(new Date(formValue.startDate), 187)),//188
        'yyyy-MM-dd'
      )
  }
}
// 结束时间选择
const handleEndTime = (e: any) => {
  formValue.endDate = e
  if (new Date(e) < new Date(formValue.startDate)) formValue.endDate = null, message.error('结束时间不允许小于开始时间')
}
// 禁用结束时间
const handleDateDisable = (ts: any) => {
  if (formValue.leaveType == 'A2605') {
    const c = formValue.destination == '省外' ? 6 : 5
    return ts > new Date(addDays(new Date(formValue.startDate), c))
  } else {
    return ts < new Date(subDays(new Date(formValue.startDate), 1))
  }
}
// 禁用开始时间
const handleDateDisableStart = (ts: any) => {
  if (!formValue.endDate) return false
  return ts > new Date(subDays(new Date(formValue.endDate), 0))
}
// 开始时间清除
const clearStartDate = () => {
  formValue.endDate = null
}
// nav点击
const selectedIndex = ref(0)
const hint: any = ref('调休假最少以0.5天为单位。')
const getTopTic = (val: any, code: any) => {
  selectedIndex.value = val
  formValue.leaveType = code
  Object.keys(formValue).map((it: any) => {
    if (it == 'leaveType' || it == 'leaveDay' || it == 'entityId' || it == 'fileIds' || it == 'draftFlag') return
    if (it == 'startSessional') return (formValue[it] = '上午')
    if (it == 'endSessional') return (formValue[it] = '下午')
    formValue[it] = null
  })
  if (['A2604', 'A2606', 'A2607', 'A2608', 'A2609', 'A2610'].includes(formValue.leaveType))
    rules.value.fileIds.required = true
  else rules.value.fileIds.required = false
  if (formValue.leaveType == 'A2604') {
    formValue.leaveDay = 3
  } else if (formValue.leaveType == 'A2606') {
    formValue.leaveDay = 158
  } else if (formValue.leaveType == 'A2607') {
    formValue.leaveDay = 15
  } else formValue.leaveDay = 0
}
watch(() => formValue.leaveType, (code: any) => {
  if (code == 'A2601') hint.value = '调休假最少以0.5天为单位。'
  else if (code == 'A2602') hint.value = '年休假最少以0.5天为单位。'
  else if (code == 'A2603') hint.value = '职工使用完年休假后可申请事假'
  else if (code == 'A2604')
    hint.value =
      '职工结婚，享受婚假三天，婚假不得分期使用，不得延至下一年度使用，需要上传结婚证原件。'
  else if (code == 'A2605')
    hint.value =
      '职工直系亲属（父母、配偶、子女）以及配偶父母去世，给予丧假3天，需杭州市外料理丧事的，可根据路程远近，另给予路程假，省内2天，省外3天。'
  else if (code == 'A2606')
    hint.value = '女职工一孩生育享受产假158天，二孩、三孩生育享受产假188天。需要上传出生证明。'
  else if (code == 'A2607')
    hint.value =
      '符合法律法规规定生育子女的夫妻，在女方生育期间，男方可享受15天的护理假；护理假应连续使用，不得分期使用，需要上传出生证明。'
  else if (code == 'A2608')
    hint.value = '在子女三周岁内，夫妻双方每年各享受十天育儿假，需要上传出生证明。'
  else if (code == 'A2609')
    hint.value =
      '独生子女家庭父母一方年满60周岁的，每年享受5天的陪护父母假。请上传父母之一的60岁身份证明。'
  else if (code == 'A2610') hint.value = '职工病假，需要上传省医保定点医院或急诊医院的病假证明。'
  else hint.value = null
})
// 类型
const supplementaryTypeList: any = ref()
const getSupplementaryTypeList = async () => {
  const [error, res] = await sendRequest<HttpResponse<LeaveModel>>({
    module: 'receiveOrDispatch',
    api: 'parentCode',
    override: {
      params: {
        dicCode: 'A26'
      }
    }
  })
  if (error) return
  if (res.code !== 0) return
  supplementaryTypeList.value = res.data
  supplementaryTypeList.value.splice(
    supplementaryTypeList.value.length - 1,
    1,
    ...supplementaryTypeList.value.splice(
      2,
      1,
      supplementaryTypeList.value[supplementaryTypeList.value.length - 1]
    )
  )
  const index = supplementaryTypeList.value.splice(1, 1)
  supplementaryTypeList.value.splice(supplementaryTypeList.value.length - 1, 0, ...index)
  if (route.path == '/OA/Leave/LeaveAdd' && props.type && props.title == '请假申请') {
    const index = supplementaryTypeList.value.findIndex((it: any) => it.dicCode == props.type)
    if (index !== -1) getTopTic(index, props.type)
  }
}
// 休息天数
const userLeaveList: any = ref({})
const getUserLeave = async () => {
  const [error, res] = await sendRequest<HttpResponse<LeaveModel>>({
    module: 'leave',
    api: 'userLeave'
  })
  if (error) return
  if (res.code !== 0) return
  userLeaveList.value = res.data
}
// 获取流程id
const spinShow = ref(false)
const workFlowList = ref(' ')
const getWorkFlow = async () => {
  spinShow.value = true
  const [error, res] = await sendRequest<HttpResponse<LeaveModel>>({
    module: 'receiveOrDispatch',
    api: 'workFlow',
    override: {
      params: {
        functionCode: formValue.leaveDay < 3 ? 'A0520' : formValue.leaveDay < 5 ? 'A0521' : 'A0522'
      }
    }
  })
  if (error) return
  if (res.code !== 0) return
  formValue.entityId = res.data.entityId
  workFlowList.value = res.data.workFlowList?.length ? res.data.workFlowList?.map((it: any) => it).join(' → ') : null
  spinShow.value = false
}
// 返回
const goBack = () => {
  const index = tags.findIndex((item: any) => item.path === router.currentRoute.value.fullPath)
  tags.splice(index, 1)
  if (tags.length == 0) {
    router.push({ path: '/OA/Workbench/UserDesktop' })
  } else history.back()
}
// 附件
const handleUploadList = async (v: any) => {
  formValue.fileIds = v
  formRef.value?.validate()
}
// 确定
const loading = ref(false)
const formRef = ref<FormInst | null>(null)
const contentContent = ref()
interface repeatFormUrlState {
  path: string;
  params: {
    [key: string] : any;
  }
}
const repeatFormUrl = reactive<repeatFormUrlState>({
  path: "",
  params: {}
}) // 是否有重复工单的url
const confirm = (status: any) => {
  formRef.value?.validate(async (err) => {
    if (err) return (contentVisible.value = false)
    if (formValue.leaveType == 'A2603' && userLeaveList.value.nxj > 0) return message.error(`您还有可用年休假${userLeaveList.value.nxj}天，请优先使用`)
    if (formValue.leaveType == 'A2602' && formValue.leaveDay > userLeaveList.value.nxj) return message.error('请假天数不允许超过假期余额')
    let startTime = null
    let endTime = null
    if (!['A2601', 'A2602', 'A2603', 'A2610', 'A2608', 'A2609'].includes(formValue.leaveType)) {
      startTime = formValue.startDate + ' ' + '07:00:00'
      endTime = formValue.endDate + ' ' + '19:00:00'
    } else {
      startTime = formValue.startSessional == '上午' ? formValue.startDate + ' ' + '07:00:00' : formValue.startDate + ' ' + '12:00:00'
      endTime = formValue.endSessional == '上午' ? formValue.endDate + ' ' + '12:00:00' : formValue.endDate + ' ' + '19:00:00'
    }
    const [error, res] = await sendRequest({
      module: 'overTime',
      api: 'getWorkOvertimeApplyCheck1',
      override: {
        data: {
          startTime,
          endTime,
          type: 2,
          ids: []
        }
      }
    })
    if (error) return message.error(error.message)
    if (res.code !== 0) return message.error(res.msg)
    // if (res.data as never !== '可以提交') return message.error(res.data as never)
    const { prompt, promptFlag, promptId, typeNumber } = (res.data as any)
    formValue.draftFlag = status
    if(promptFlag) {
      contentVisible.value = true
      contentContent.value = prompt
      if(typeNumber !== 0) {
        if(typeNumber == 2) {
          repeatFormUrl.path = '/OA/Leave/LeaveInfo',
          repeatFormUrl.params = { id: promptId }
        }
      }
    } else {
      // contentContent.value = status ? '您确定要保存草稿吗？' : ' 您确定要提交申请吗？'
      submit()
    }
  })
}
// 打开重复的url
const openRepeatUrl = () => {
  if(repeatFormUrl) {
    router.push({ path: repeatFormUrl.path, query: { ...repeatFormUrl.params } })
    contentVisible.value = false
    repeatFormUrl.path = ''
    repeatFormUrl.params = {}
  }
}
// 提交
const contentVisible = ref(false)
const submit = async () => {
  const params = JSON.parse(JSON.stringify(formValue))
  if (!['A2601', 'A2602', 'A2603', 'A2608', 'A2609', 'A2610'].includes(params.leaveType))
    params.startSessional = null, params.endSessional = null
  if ((props.id && props.flat) || (!props.id && !props.flat)) {
    loading.value = true
    contentVisible.value = false
    const [error, res] = await sendRequest<HttpResponse<LeaveModel>>({
      module: 'leave',
      api: 'leaveAdd',
      override: {
        data: {
          ...params,
          functionCode:
            formValue.leaveDay < 3 ? 'A0520' : formValue.leaveDay < 5 ? 'A0521' : 'A0522'
        }
      }
    })
    loading.value = false
    if (error) return message.error(error.message)
    if (res.code !== 0) return message.error(res.msg)
    message.success('保存成功')
  } else {
    loading.value = true
    contentVisible.value = false
    const [error, res] = await sendRequest<HttpResponse<LeaveModel>>({
      module: 'leave',
      api: 'leaveUpdate',
      override: {
        data: {
          ...params,
          functionCode:
            formValue.leaveDay < 3 ? 'A0520' : formValue.leaveDay < 5 ? 'A0521' : 'A0522',
          id: props.id
        }
      }
    })
    loading.value = false
    if (error) return message.error(error.message)
    if (res.code !== 0) return message.error(res.msg)
    message.success('保存成功')
  }
  goSubmit()
}

//提交完跳转我的提交
const goSubmit = () => {
  const index = tags.findIndex((item: any) => item.path === router.currentRoute.value.fullPath)
  tags.splice(index, 1)
  if (formValue.draftFlag) return router.push({ path: '/OA/UserCenter/Drafts' })
  router.push({ path: '/OA/UserCenter/Submit' })
}

// 获取修改详情
const fileList: any = ref([])
const getDispatchInfo = async () => {
  spinShow.value = true
  const [error, res] = await sendRequest<HttpResponse<LeaveModel>>({
    module: 'leave',
    api: 'leaveInfo',
    uri: {
      id: props.id
    }
  })
  if (error) return message.error(error.message), (spinShow.value = false)
  if (res.code !== 0) return message.error(res.msg), (spinShow.value = false)
  fileList.value = res.data?.fileList
  Object.keys(formValue).map((it: any) => {
    // if (it == 'leaveDay' || it == 'entityId') return
    // @ts-ignore
    if (it == 'startDate' || it == 'endDate') return (formValue[it] = res.data[it].split(' ')[0])
    // @ts-ignore
    formValue[it] = res.data[it]
  })
  selectedIndex.value = supplementaryTypeList.value?.findIndex(
    (it: any) => it.dicCode == res.data.leaveType
  )
  if (['A2604', 'A2606', 'A2607', 'A2608', 'A2609', 'A2610'].includes(formValue.leaveType))
    rules.value.fileIds.required = true
  else rules.value.fileIds.required = false
  getWorkFlow()
}
// icon的图标
const handleSrc = (index: any, code: any) => {
  if (code == 'A2601' && index == selectedIndex.value) return A2601F
  else if (code == 'A2601') return A2601
  else if (code == 'A2602' && index == selectedIndex.value) return A2602F
  else if (code == 'A2602') return A2602
  else if (code == 'A2603' && index == selectedIndex.value) return A2603F
  else if (code == 'A2603') return A2603
  else if (code == 'A2604' && index == selectedIndex.value) return A2604F
  else if (code == 'A2604') return A2604
  else if (code == 'A2605' && index == selectedIndex.value) return A2605F
  else if (code == 'A2605') return A2605
  else if (code == 'A2606' && index == selectedIndex.value) return A2606F
  else if (code == 'A2606') return A2606
  else if (code == 'A2607' && index == selectedIndex.value) return A2607F
  else if (code == 'A2607') return A2607
  else if (code == 'A2608' && index == selectedIndex.value) return A2608F
  else if (code == 'A2608') return A2608
  else if (code == 'A2609' && index == selectedIndex.value) return A2609F
  else if (code == 'A2609') return A2609
  else if (code == 'A2610' && index == selectedIndex.value) return A2610F
  else if (code == 'A2610') return A2610
}

// 计算请假天数
watch(() => [formValue.startDate, formValue.endDate, formValue.startSessional, formValue.endSessional,
formValue.leaveType], async () => {

  if (!formValue.startDate || !formValue.endDate) return
  if (formValue.startDate == formValue.endDate && formValue.startSessional == '下午' && formValue.endSessional == '上午') {
    (formValue.startSessional = null, formValue.endSessional = null, message.error('时间选择错误！'))
    return
  }

  if (['A2601', 'A2602', 'A2603', 'A2608', 'A2609', 'A2610'].includes(formValue.leaveType)) {
    // if (formValue.startSessional == null || formValue.endSessional == null) return
    const [error, res] = await sendRequest<HttpResponse<LeaveModel>>({
      module: 'leave',
      api: 'getLeaveCountDay',
      override: {
        data: {
          endDate: formValue.endDate,
          endSessional: formValue.leaveType != 'A2605' ? formValue.endSessional : null,
          startDate: formValue.startDate,
          startSessional: formValue.leaveType != 'A2605' ? formValue.startSessional : null
        }
      }
    })
    if (error) return
    if (res.code !== 0) return

    return formValue.leaveDay = res.data
  } else if (formValue.leaveType == 'A2605') {
    formValue.leaveDay = differenceInDays(new Date(formValue.endDate), new Date(formValue.startDate)) + 1
  }

}, { deep: true, immediate: true })

watch(
  () => formValue.leaveDay,
  () => {
    getWorkFlow()
  }
)

watch(
  () => formValue.childCon,
  () => {
    if (formValue.childCon == '一孩') formValue.leaveDay = 158
    else if (formValue.childCon == '二孩/三孩') formValue.leaveDay = 188
  }
)

watch(
  () => props.id,
  async () => {
    if (props.title == '请假编辑' && props.id) {
      await getSupplementaryTypeList()
      await getDispatchInfo()
      getUserLeave()
    }
    if (props.title == '请假申请') {
      getSupplementaryTypeList()
      getUserLeave()
      getWorkFlow()
    }
  },
  { deep: true, immediate: true }
)

</script>

<style scoped lang="scss">
@mixin CommonFont {
  font-size: 16rem;
  font-family: PingFangSC, PingFang SC;
  font-weight: 400;
  color: rgba(0, 0, 0, 0.85);
}

.commonWidth {
  width: 240rem;
}

.main {
  display: flex;
  flex-direction: column;
  width: 100%;
  height: 100%;
  overflow: hidden;

  .topTitle {
    width: 100%;
    border-bottom: 1px solid #fff;
    padding: 15rem 20rem;
    margin-bottom: 20rem;
    @include CommonFont;
  }

  .form_content {
    width: 100%;
    height: 100%;
    padding: 0 20rem 0rem;

    .content {
      display: flex;
      flex-wrap: wrap;
      padding: 20rem 0 180rem;
      background-color: #ebeceb;


      .scope {
        display: flex;
        flex-wrap: wrap;
        width: 100%;

        .userBox {
          display: flex;
          justify-content: space-between;
          align-items: center;
          width: 100%;
          height: 40rem;
          background-color: #fff;
          border-radius: 4rem;
          padding: 5px 10rem;
          margin-bottom: 10rem;
        }
      }
    }
  }
}

.content_cen {
  display: flex;
  flex-direction: column;
  margin-left: 35%;
}

.iconStyle {
  margin-right: 5rem;
  color: #5fb17f;
}

.progress {
  display: flex;
  align-items: center;
  min-width: 350rem;
  max-width: 800rem;
  min-height: 50rem;
  background-color: #d5e2d8;
  border-radius: 5rem;
  margin-bottom: 10px;
  padding: 5px 15px;
  margin-left: 35%;
}

.progressHint {
  display: flex;
  min-width: 350rem;
  max-width: 800rem;
  padding: 10px 15px;
  margin-left: 35%;
}

.content::-webkit-scrollbar {
  display: none;
}

:deep(.n-spin-container) {
  width: 100%;
  height: 100%;
}

:deep(.n-scrollbar-container) {
  width: 100%;
  height: 100%;
}

:deep(.n-spin-content) {
  width: 100%;
  height: 100%;
}

.top-select {
  display: flex;
  justify-content: space-around;
  width: 60vw;
  height: 60rem;
  background-color: #d5e3d8;
  border-radius: 10rem;
  padding: 5rem 0;
  margin-left: 14.5%;

  .select-item {
    width: 100rem;
    display: flex;
    align-items: center;
    justify-content: center;
    border-radius: 10rem;
    color: #333333;
    cursor: pointer;
  }

  .active {
    background-color: #5fb17f;
    color: #fff;
    cursor: pointer;
  }
}
</style>
